import Java from "frida-java-bridge";
import { Logger } from "./log.js";

const TAG = "Utils";

/**
 * 获取当前进程的包名
 */
export function getSelfPackageName() {
  let libc;
  try {
    libc = Process.getModuleByName("libc.so");
  } catch (e) {
    Logger.w(TAG, "[Dump] libc.so not found.");
    return "-1";
  }
  // var fgetsPtr = libc.getExportByName("fgets");
  var openPtr = libc.getExportByName("open");
  var open = new NativeFunction(openPtr, "int", ["pointer", "int"]);

  var readPtr = libc.getExportByName("read");
  var read = new NativeFunction(readPtr, "int", ["int", "pointer", "int"]);

  var closePtr = libc.getExportByName("close");
  var close = new NativeFunction(closePtr, "int", ["int"]);

  //申请字符串空间，声明字符串
  var path = Memory.allocUtf8String("/proc/self/cmdline");
  var fd = open(path, 0);
  if (fd != -1) {
    var buffer = Memory.alloc(0x1000);
    read(fd, buffer, 0x1000);
    close(fd);

    //读取c风格字符串，会被/0截断字符串，从而拿到包名
    var line = buffer.readCString();
    Logger.i(TAG, "[Package] " + line);

    return line;
  }

  return "-1";
}

/**
 * 在 ClassLoader 中，遍历所有的类！
 */
export function processClassLoader(classloader: any) {
  try {
    var DexFile = Java.use("dalvik.system.DexFile");
    var BaseDexClassLoader = Java.use("dalvik.system.BaseDexClassLoader");
    var DexPathList = Java.use("dalvik.system.DexPathList");
    var Element = Java.use("dalvik.system.DexPathList$Element");
    var basedexclassloaderobj = Java.cast(classloader, BaseDexClassLoader);

    var tmpobj = basedexclassloaderobj.pathList.value;
    var pathlistobj = Java.cast(tmpobj, DexPathList);
    var dexElementsobj = pathlistobj.dexElements.value;

    if (dexElementsobj != null) {
      for (var i in dexElementsobj) {
        var obj = dexElementsobj[i];
        var elementobj = Java.cast(obj, Element);
        tmpobj = elementobj.dexFile.value;
        var dexfileobj = Java.cast(tmpobj, DexFile);
        const enumeratorClassNames = dexfileobj.entries();
        while (enumeratorClassNames.hasMoreElements()) {
          var className = enumeratorClassNames.nextElement().toString();
          // TODO: 如何处理这些类？
          console.log("start loadclass->", className);
          var loadclass = classloader.loadClass(className);
          console.log("after loadclass->", loadclass);
        }
      }
    }
  } catch (e) {
    console.log(e);
  }
}
